package zmee.pur.src.formplugin;

import com.alibaba.druid.util.StringUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.interaction.InteractionContext;
import kd.bos.form.CloseCallBack;
import kd.bos.form.MessageTypes;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.orm.query.QFilter;
import kd.bos.orm.util.CollectionUtils;
import kd.bos.util.JSONUtils;
import kd.scm.pds.common.enums.SourceTypeEnums;
import kd.scm.pds.common.util.OpenFormUtils;
import kd.scm.src.common.util.SrcDemandUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2022/12/15/20:53
 * @Description: 招标立项申请单下一步按钮下拉过滤，自动跳转项目启动列表
 */
public class DemandBillPlugin extends AbstractBillPlugIn {

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        FormOperate formOperate = (FormOperate) args.getSource();
        String operateKey = formOperate.getOperateKey();
        if (args.getOperationResult() != null && args.getOperationResult().isSuccess()) {
            if (StringUtils.equals("negocuate", operateKey)) {
                extracted(args, "C010415");
            } else if (StringUtils.equals("government", operateKey)) {
                extracted(args, "C010417");
            } else if (StringUtils.equals("inquiry", operateKey)) {
                extracted(args, "C010418");
            } else if (StringUtils.equals("parity", operateKey)) {
                extracted(args, "C010416");
            }
        }
    }

    private void extracted(AfterDoOperationEventArgs args, String sourceType) {
        InteractionContext interactionContext = args.getOperationResult().getInteractionContext();
        if (interactionContext != null) {
            Map<String, String> resutlMap = interactionContext.getCustShowParameter();
            if (resutlMap != null && resutlMap.size() != 0) {
                String title = (String) resutlMap.get("title");
                String message = (String) resutlMap.get("message");
                if (!Boolean.parseBoolean((String) resutlMap.get("succed"))) {
                    this.getView().showMessage(title, message, MessageTypes.Default);
                } else {
                    Object sceneObj = resutlMap.get("sceneIds");
                    if (Objects.nonNull(sceneObj)) {
                        Map sceneMap = new HashMap<>(8);

                        try {
                            sceneMap = JSONUtils.cast(String.valueOf(sceneObj), Map.class);
                        } catch (IOException ignored) {
                        }

                        if (!CollectionUtils.isEmpty(sceneMap)) {
                            ((Map) sceneMap).forEach((key, value) -> {
                                SrcDemandUtils.updateSceneStatus((String) key, (String) value, "B");
                            });
                        }
                    }

                    Map<String, Object> paramMap = new HashMap<>(1);
                    paramMap.put("message", title + "：" + message);
                    OpenFormUtils.openListPage(this.getView(), "src_project", ShowType.MainNewTabPage, paramMap,
                            setProjectListFilter(sourceType), (CloseCallBack) null);
                }
            }
        }
    }

    private static QFilter setProjectListFilter(String sourceType) {
        return new QFilter("sourcetype.number", "=", sourceType);
    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        this.setButtonVisible();
    }

    private void setButtonVisible() {
        DynamicObjectCollection rows = this.getModel().getEntryEntity("entry");
        Set<String> purTypes =
                rows.stream().map((row) -> Optional.ofNullable(row.getDynamicObject("purtype")).map((type) -> type.getString("number")).orElse((String) null)).filter(Objects::nonNull).collect(Collectors.toSet());
        for (String number : purTypes) {
            switch (number) {
                case "C010415":
                    this.getView().setVisible(Boolean.TRUE, "negocuate");
                    break;
                case "C010417":
                    this.getView().setVisible(Boolean.TRUE, "Government");
                    break;
                case "C010418":
                    this.getView().setVisible(Boolean.TRUE, "Inquiry");
                    break;
                case "C010416":
                    this.getView().setVisible(Boolean.TRUE, "parity");
                    break;
                default:
                    String type = SourceTypeEnums.getName(number);
                    this.getView().setVisible(Boolean.TRUE, type.replace("_", "").toLowerCase());
            }
        }

        Set<String> typeEnums = Arrays.stream(SourceTypeEnums.values()).map(SourceTypeEnums::getValue).collect(Collectors.toSet());
        typeEnums.add("C010415");
        typeEnums.add("C010417");
        typeEnums.add("C010418");
        typeEnums.add("C010416");
        typeEnums.removeAll(purTypes);
        for (String number : typeEnums) {
            switch (number) {
                case "C010415":
                    this.getView().setVisible(Boolean.FALSE, "negocuate");
                    break;
                case "C010417":
                    this.getView().setVisible(Boolean.FALSE, "Government");
                    break;
                case "C010418":
                    this.getView().setVisible(Boolean.FALSE, "Inquiry");
                    break;
                case "C010416":
                    this.getView().setVisible(Boolean.FALSE, "parity");
                    break;
                default:
                    String sourceType = SourceTypeEnums.getName(number);
                    this.getView().setVisible(Boolean.FALSE, sourceType.replace("_", "").toLowerCase());
            }
        }
    }
}